//
//  MoreViewController.m
//  IntimateGift
//
//  Created by zh on 14/12/22.
//  Copyright (c) 2014年 蔡宏业. All rights reserved.
//

#import "MoreViewController.h"
#import "UIColor+AddColor.h"
#import "WeViewController.h"
#import "SDImageCache.h"
//#import <ShareSDK/ShareSDK.h>
#import "AppDelegate.h"
#import "WeiboSDK.h"
#import <MessageUI/MessageUI.h>

#define MOREREUSE @"moreReuse"

@interface MoreViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, MFMailComposeViewControllerDelegate>

@property (nonatomic, retain) UITableView *myTableView;

@property (nonatomic, retain) NSMutableArray *arr;

@property (nonatomic, retain) NSMutableArray *imageArr;

@property (nonatomic, retain) NSMutableArray *array;

@end

@implementation MoreViewController


- (void)dealloc
{
    [_arr release];
    [_myTableView release];
    [_imageArr release];
    [_array release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self= [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arr = [NSMutableArray arrayWithObjects:@"分享", @"反馈", @"关于我们", nil];
        self.array = [NSMutableArray arrayWithObjects:@"清空缓存", @"检测版本", nil];
//        self.state = NO;
//        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//        [center addObserver:self selector:@selector(receiveNotifica:) name:@"tamenlaile" object:nil];
    }
    return self;
}

- (void)receiveNotifica:(NSNotification *)center
{
    self.state = YES;
    NSLog(@"111");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"更多";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
    self.navigationController.navigationBar.barTintColor = [UIColor ownColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(doneBarItemClicked:)] autorelease];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
//    [view release];
    
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:MOREREUSE];
    
    [_myTableView release];
    
    // Do any additional setup after loading the view.
}

- (void)cancelButtonClicked:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)doneBarItemClicked:(UIBarButtonItem *)item
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.arr.count;
    } else {
        return self.array.count;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MOREREUSE];
    if (indexPath.section == 0) {
        cell.textLabel.text = [self.arr objectAtIndex:indexPath.row];
        if (indexPath.row == 0) {
            cell.imageView.image = [UIImage imageNamed:@"iconfont-fenxiang.png"];
        } else if (indexPath.row == 1) {
            cell.imageView.image = [UIImage imageNamed:@"iconfont-fankui.png"];
        } else if (indexPath.row == 2) {
            cell.imageView.image = [UIImage imageNamed:@"iconfont-guanyuabout.png"];
        }
    } else {
        cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
        if (indexPath.row == 0) {
            cell.imageView.image = [UIImage imageNamed:@"iconfont-qingchuyuhuancun.png"];
        } else if (indexPath.row == 1) {
            cell.imageView.image = [UIImage imageNamed:@"iconfont-banbengengxin.png"];
        }
    }
    return cell;
}

- (WBMessageObject *)messageToShare
{
    WBMessageObject *message = [WBMessageObject message];
    NSString *str = @"IntimateGift真的是一款很好很赞的软件哦！";
    message.text = str;
    WBImageObject *image = [WBImageObject object];
    image.imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"duolaameng" ofType:@"jpg"]];
    message.imageObject = image;
    return message;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
//            if (self.state == NO) {
//            
//                // 分享
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请登录后分享" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//                [alertView show];
//                [alertView release];
//            }
            
//            NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"jpg"];
//            
//            //1、构造分享内容
//            id<ISSContent> publishContent = [ShareSDK content:@"IntimateGift真的是一款很好很赞的软件哦！"
//                                               defaultContent:@"默认内容"
//                                                        image:[ShareSDK imageWithPath:imagePath]
//                                                        title:@"ShareSDK"
//                                                          url:@"http://www.mob.com"
//                                                  description:@"这是一条演示信息"
//                                                    mediaType:SSPublishContentMediaTypeNews];
//            //1+创建弹出菜单容器（iPad必要）
//            id<ISSContainer> container = [ShareSDK container];
//            [container setIPadContainerWithView:tableView arrowDirect:UIPopoverArrowDirectionUp];
//            
//            //2、弹出分享菜单
//            [ShareSDK showShareActionSheet:container
//                                 shareList:nil
//                                   content:publishContent
//                             statusBarTips:NO
//                               authOptions:nil
//                              shareOptions:nil
//                                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
//                                        
//                                        //可以根据回调提示用户。
//                                        if (state == SSResponseStateSuccess)
//                                        {
//                                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享成功"
//                                                                                            message:nil
//                                                                                           delegate:self
//                                                                                  cancelButtonTitle:@"OK"
//                                                                                  otherButtonTitles:nil, nil];
//                                            [alert show];
//                                            [ShareSDK getUserInfoWithType:ShareTypeSinaWeibo authOptions:[ShareSDK authOptionsWithAutoAuth:YES allowCallback:YES authViewStyle:SSAuthViewStyleFullScreenPopup viewDelegate:self authManagerViewDelegate:self] result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
//                                                if (result) {
//                                                    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"注销" style:1 target:self action:@selector(logoutButton:)] autorelease];
//                                                }
//                                            }];
//
//                                        }
//                                        else if (state == SSResponseStateFail)
//                                        {
//                                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
//                                                                                            message:[NSString stringWithFormat:@"失败描述：%@",[error errorDescription]]
//                                                                                           delegate:self
//                                                                                  cancelButtonTitle:@"OK"
//                                                                                  otherButtonTitles:nil, nil];
//                                            [alert show];
//                                        }
//                                    }];
//            if (self.state == YES) {
            
                AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
                
                WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
                authRequest.redirectURI = @"http://open.weibo.com";
                authRequest.scope = @"all";
                
                WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
                request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                                     @"Other_Info_1": [NSNumber numberWithInt:123],
                                     @"Other_Info_2": @[@"obj1", @"obj2"],
                                     @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
                //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
                [WeiboSDK sendRequest:request];
//            }
//            
//            NSLog(@"%d", self.state);
//            
        } else if (indexPath.row == 1) {
            // 反馈
            
            if ([MFMailComposeViewController canSendMail]) {
                
                MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
                picker.mailComposeDelegate = self;
                
                [picker setSubject:@"Enter Your Subject!"];
                
                // Set up recipients
                NSArray *toRecipients = [NSArray arrayWithObject:@"zhouhang9282@163.com"];
                
                
                [picker setToRecipients:toRecipients];
                
                // Attach an image to the email
//                NSString *path = [[NSBundle mainBundle] pathForResource:@"" ofType:@"png"];
//                NSData *myData = [NSData dataWithContentsOfFile:path];
//                [picker addAttachmentData:myData mimeType:@"image/png" fileName:@""];
                
                // Fill out the email body text
                
                [self presentViewController:picker animated:YES completion:^{
                    
                }];
                
            } else {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请在您的设置中打开“邮件”！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
                [alertView release];
            }
            
        } else if (indexPath.row == 2) {
            // 关于我们
            WeViewController *weVC = [[WeViewController alloc] init];
            
            [self.navigationController pushViewController:weVC animated:YES];
//            [self presentViewController:weVC animated:YES completion:^{
//                
//            }];
            [weVC release];
        }
        
    } else {
        if (indexPath.row == 0) {
            
            // 清除缓存
            float a = [[SDImageCache sharedImageCache] checkTmpSize];
            [[SDImageCache sharedImageCache] clearDisk];
            NSString *str = [NSString stringWithFormat:@"缓存清除成功, 大小为%.2fMB", a];
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [alertView release];
        } else if (indexPath.row == 1) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您的版本是最新版本" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [alertView release];
            
//            NSLog(@"111");
//            dispatch_queue_t mainQueue = dispatch_get_main_queue();
//            dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//            NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
//            //CFShow((__bridge CFTypeRef)(infoDic));
//            NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
//            dispatch_async(globalQueue, ^{
//                
//                NSString *URL = @"http://itunes.apple.com/lookup?id=9765557";
//                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//                [request setURL:[NSURL URLWithString:URL]];
//                [request setHTTPMethod:@"POST"];
//                NSHTTPURLResponse *urlResponse = nil;
//                NSError *error = nil;
//                NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
//                
//                //            NSString *results = [[NSString alloc] initWithBytes:[recervedData bytes] length:[recervedData length] encoding:NSUTF8StringEncoding];
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:recervedData options:NSJSONReadingMutableContainers error:&error];
//                NSArray *infoArray = [dic objectForKey:@"results"];
//                NSLog(@"%@", infoArray);
//                if ([infoArray count]) {
//                    NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
//                    NSString *lastVersion = [releaseInfo objectForKey:@"version"];
//                    
//                    if (![lastVersion isEqualToString:currentVersion]) {
//                        //trackViewURL = [releaseInfo objectForKey:@"trackVireUrl"];
//                        dispatch_async(mainQueue, ^{
//                            
//                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
//                            alert.tag = 10000;
//                            [alert show];
//                        });
//                    }
//                    else
//                    {
//                        dispatch_async(mainQueue, ^{
//                            
//                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"此版本为最新版本" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                            alert.tag = 10001;
//                            [alert show];
//                        });
//                    }
//                }
//            });
//            
        }
        
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==10000) {
        if (buttonIndex==1) {
            NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com"];
            [[UIApplication sharedApplication]openURL:url];
        }
    }
}


- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发送成功！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alertView show];
//        [alertView release];
    }];
}


//- (void)logoutButton:(UIButton *)button
//{
////    [ShareSDK cancelAuthWithType:ShareTypeSinaWeibo];
//    [self.navigationController popViewControllerAnimated:YES];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
